package com.yc.io.pdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * author: yc
 * description: ${description}
 * date: 2021/11/1 14:29
 */
public class ChangePdf2 {
    public static  void main(String[] args) {
        //模板路径
        String templatePath = "D:\\source\\word\\项目\\other\\pdf4_input.pdf";
        //生成的新文件路径
        String newPDFPath = "D:\\source\\word\\项目\\other\\pdf4_out.pdf";
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            out = new FileOutputStream(newPDFPath);//输出流
            reader = new PdfReader(templatePath);//读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            BaseFont baseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(baseFont);

            Map<String, String> map = new HashMap<>();
            map.put("userName", "张三");
            map.put("carPlate", "浙B12345");
            map.put("date", "2021-09-09");

            fillPdfCellForm(map, form);

            stamper.setFormFlattening(true);//如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.close();

            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage1 = copy.getImportedPage(
                    new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage1);
            PdfImportedPage importPage2 = copy.getImportedPage(
                    new PdfReader(bos.toByteArray()), 2);
            copy.addPage(importPage2);
            doc.close();

        } catch (IOException e) {
            System.out.println(1);
        } catch (DocumentException e) {
            System.out.println(2);
        }
    }

    private static void fillPdfCellForm(Map<String, String> map, AcroFields form) throws IOException, DocumentException {
        for (Map.Entry entry : map.entrySet()) {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            form.setField(key, value);
        }
    }
}
